package v1

import (
	"gin_mall/pkg/utils"
	"gin_mall/service"

	"github.com/gin-gonic/gin"
)

// 注册用户
func UserRegister(ctx *gin.Context) {
	var userRegisterService service.UserService
	if err := ctx.ShouldBind(&userRegisterService); err == nil {
		res := userRegisterService.Register(ctx.Request.Context())
		ctx.JSON(200, res)
	} else {
		ctx.JSON(400, ErrorResponse(err))
	}
}

// 用户登录
func UserLogin(ctx *gin.Context) {
	var userLoginService service.UserService
	if err := ctx.ShouldBind(&userLoginService); err == nil {
		res := userLoginService.Login(ctx.Request.Context())
		ctx.JSON(200, res)
	} else {
		ctx.JSON(400, ErrorResponse(err))
	}
}

// 更新用户的昵称
func UserUpdate(ctx *gin.Context) {
	var userUpdateService service.UserService
	claims, _ := ctx.Get("token")
	if err := ctx.ShouldBind(&userUpdateService); err == nil {
		res := userUpdateService.Update(ctx.Request.Context(), claims.(utils.Claims).Id)
		ctx.JSON(200, res)
	} else {
		ctx.JSON(400, ErrorResponse(err))
	}
}

// 邮箱验证
func ValidEmail(ctx *gin.Context) {
	var validEmailService service.ValidEmailService
	if err := ctx.Bind(&validEmailService); err == nil {
		res := validEmailService.Valid(ctx.Request.Context(), ctx.Query("token"))
		ctx.JSON(200, res)
	} else {
		ctx.JSON(400, ErrorResponse(err))
	}
}

// 发送邮箱 (1.用户激活 2.解绑邮箱 3.绑定邮箱 4.更改密码)
func SendEmail(ctx *gin.Context) {
	var sendEmailService service.SendEmailService
	if err := ctx.Bind(&sendEmailService); err == nil {
		res := sendEmailService.Send(ctx.Request.Context())
		ctx.JSON(200, res)
	} else {
		ctx.JSON(400, ErrorResponse(err))
	}
}

// 上传头像
func UploadAvatar(ctx *gin.Context) {
	file, fileHeader, err := ctx.Request.FormFile("file")
	if err != nil {
		ctx.JSON(400, ErrorResponse(err))
	} else {
		var uploadAvatarService service.UserService
		if err := ctx.Bind(&uploadAvatarService); err == nil {
			claims, _ := ctx.Get("token")
			res := uploadAvatarService.Post(ctx.Request.Context(), claims.(utils.Claims).Id, file, fileHeader.Filename)
			ctx.JSON(200, res)
		} else {
			ctx.JSON(400, ErrorResponse(err))
		}
	}
}
